/**
 * @author 黄波
 * 创建日期：2011Oct 8, 2011
 * TODO// N/A
 */
package com.platform.njcc.action;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.platform.pojo.DownloadRecord;
import com.platform.pojo.ResInfo;
import com.platform.pojo.UserInfo;
import com.platform.res.bo.ResBo;
import com.platform.user.bo.UserBo;

/**
 * 资源下载
 */
public class DownloadAction extends NJCCSuport {

	private String id;	//申请下载的资源ID

	@Override
	public String execute() throws Exception {
		//判断当前用户有没有登录
		HttpSession session = ServletActionContext.getRequest().getSession();
		UserInfo user = (UserInfo) session.getAttribute("user");
		if(user == null) {
			HttpServletRequest request = ServletActionContext.getRequest();
			String reqURI = "njcc/loadResItem.action"+ "?id=" + id;
//			String reqURL = request.getRequestURL().toString() + "?id=" + id;
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.flush();
			out.write("<script>alert('请在登录后下载！');window.location.href=\""+ ServletActionContext.getServletContext().getContextPath() + "/" +"login.jsp?refreshurl=" + reqURI + "\";</script>");
			out.close();
			return null;
		}

		if(user.getIsAudit().intValue() != 1) {
			//用户未登录
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.flush();
			out.write("<script>alert('帐户锁定中，不能下载资源，请联系管理员解锁！');history.back();;</script>");
			out.close();
			return null;
		}
		if(id == null || id.equals("")) {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.flush();
			out.write("<script>alert('资源信息为空！');history.back();</script>");
			out.close();
			return null;
		}
		HttpServletResponse response = ServletActionContext.getResponse();
		ResBo resBo = ResBo.getInstance();
		ResInfo info = resBo.getInfo(id);
		//查看该用户是否有下载权限
		if(info.getShareWay() == 1) {
			//该资源为课程资源
			//取资源所对应班级
			Integer resClassId = info.getClassId();
			//取当前要下载该资源的用户的班级
			Integer userClassId = user.getClassId();
			if(resClassId != userClassId) {
				response.setCharacterEncoding("utf-8");
				response.setContentType("text/html");
				PrintWriter out = response.getWriter();
				out.flush();
				out.write("<script>alert('非该班级人员无权下载此文件！');history.back();</script>");
				out.close();
				return null;
			}
		}
		//取用户下载记录，如已有下载记录，则直接进行下载
		DownloadRecord record = resBo.getDownloadRecord(user.getId(), info.getId());
		if(record != null || user.getId().intValue() == info.getUploadUserId().intValue()) {
			//已有下载记录或当前下载者为上传者，则直接进行下载
			String path = ServletActionContext.getServletContext().getRealPath(info.getAttachUrl()); 
	        
	        File fileToDown = new File(path); 
	        if(!fileToDown.exists()) {
				response.setCharacterEncoding("utf-8");
				response.setContentType("text/html");
				PrintWriter out = response.getWriter();
				out.flush();
				out.write("<script>alert('资源不存在或已被删除！');history.back();</script>");
				out.close();
				return null;
	        }
	        ServletOutputStream out = response.getOutputStream(); 
	        FileInputStream fileIn = new FileInputStream(fileToDown); 
	        BufferedInputStream buffer = new BufferedInputStream(fileIn); 
	        int fileLength = fileIn.available(); 
	        byte[] fileBytes = new byte[1024]; 
	        //设置文件大小 
	        response.reset();
	        response.setCharacterEncoding("utf-8");
	        response.setContentLength(fileLength); 
	        response.setContentType("application/x-msdownload");   
	        response.addHeader("Content-Disposition","attachment; filename=\"" + URLEncoder.encode(info.getName(), "utf-8") + "\""); 
	        //输出文件流 
	        while   (true)   { 
	                int   isOver   =   buffer.read(fileBytes); 
	                out.write(fileBytes); 
	                if (isOver   ==   -1) {
	                     break; 
	                }
	        } 
	        buffer.close();
	        out.close(); 
	        return null;
		}
		//判断当前用户积分是否满足下载条件
		if(user.getScore() < info.getReqPoint()) {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.flush();
			out.write("<script>alert('你当前积分不足！');history.back();</script>");
			out.close();
			return null;
		}
		
		String path = ServletActionContext.getServletContext().getRealPath(info.getAttachUrl()); 
        
        File fileToDown = new File(path); 
        if(!fileToDown.exists()) {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			PrintWriter out = response.getWriter();
			out.flush();
			out.write("<script>alert('资源不存在或已被删除！');history.back();</script>");
			out.close();
			return null;
        }
        ServletOutputStream out = response.getOutputStream(); 
        FileInputStream fileIn = new FileInputStream(fileToDown); 
        BufferedInputStream buffer = new BufferedInputStream(fileIn); 
        int fileLength = fileIn.available(); 
        byte[] fileBytes = new byte[1024]; 
        //设置文件大小 
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.setContentLength(fileLength); 
        response.setContentType("application/x-msdownload");   
        response.addHeader("Content-Disposition","attachment; filename=\"" + URLEncoder.encode(info.getName(), "utf-8") + "\""); 
        //输出文件流 
        while   (true)   { 
                int   isOver   =   buffer.read(fileBytes); 
                out.write(fileBytes); 
                if (isOver   ==   -1) {
                     break; 
                }
        } 
        buffer.close();
        out.close(); 
        //下載成功后，更新數據庫中下載次數
        info.setDownloadCount(info.getDownloadCount() + 1);
        resBo.updateInfo(info);
		//更新资源发布人信息(修改一系列信息)
        UserBo userBo = UserBo.getInstance();
        UserInfo ownner = userBo.getUser(info.getUploadUserId().toString());
        ownner.setScore(ownner.getScore() + info.getReqPoint());
        ownner.setDownloadedCount(ownner.getDownloadedCount() + 1);
        userBo.updateUser(ownner);
        //更新下载人信息
        user.setScore(user.getScore() - info.getReqPoint());
        user.setDownloadCount(user.getDownloadCount() + 1);
        user.setUserScore(user.getUserScore() + info.getReqPoint());
        userBo.updateUser(user);
        //写下载流水记录
        DownloadRecord dr = new DownloadRecord();
        dr.setUserId(user.getId());
        dr.setResId(info.getId());
        dr.setDownloadTime(new Date());
        resBo.addDownloadRecord(dr);
		return null;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	
}
